<?php
namespace backend\controllers;

use common\models\Statistics;
use common\utils\XCache;
use common\utils\XFile;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error', 'captcha', 'authority', 'clear-cache', 'clear-assets'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                'height' => '34'
            ]
        ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        //站点统计
        $sTime = date('Y-m-d', strtotime('-7 days'));//默认7天前
        $eTime = date('Y-m-d');
        if (Yii::$app->request->post('sTime')) {
            $sTime = Yii::$app->request->post('sTime');
        }
        if (Yii::$app->request->post('eTime')) {
            $eTime = Yii::$app->request->post('eTime');
        }
        $sTime = strtotime($sTime);
        $eTime = strtotime($eTime) + 24 * 3600;//加上24小时

        //先找出所有的记录再处理
        $dataList = Statistics::find()->where("ctime>=" . $sTime . " and ctime<=" . $eTime)->asArray()->all();
        //计算每天的pv/uv
        $pvList = $uvList = [];
        foreach ((array)$dataList as $key => $item) {
            $pvList[date('Y-m-d', $item['ctime'])][] = $item;
            $uvList[date('Y-m-d', $item['ctime'])][$item['tid']] = $item;
        }

        $pvLabels = $pvDatas = '[';
        $uvLabels = $uvDatas = '[';
        foreach ($pvList as $key => $item) {
            $pvDatas .= count($item) . ',';
            $pvLabels .= "'" . $key . "',";

            $uvDatas .= count($uvList[$key]) . ',';
            $uvLabels .= "'" . $key . "',";
        }
        $pvLabels = rtrim($pvLabels, ',') . ']';
        $pvDatas = rtrim($pvDatas, ',') . ']';
        $uvLabels = rtrim($uvLabels, ',') . ']';
        $uvDatas = rtrim($uvDatas, ',') . ']';
        //站点统计 END

        return $this->render('index', [
            'pvList' => ['labels' => $pvLabels, 'data' => $pvDatas],
            'uvList' => ['labels' => $uvLabels, 'data' => $uvDatas],
            'sTime' => date('Y-m-d', $sTime),
            'eTime' => date('Y-m-d', $eTime - 24 * 3600)
        ]);
    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * 没有权限
     * @return string
     */
    public function actionAuthority()
    {
        return $this->render('authority');
    }

    /**
     * 清空缓存
     */
    public function actionClearCache()
    {
        if (Yii::$app->request->isPost) {
            if (XCache::flush() && XFile::delCache()) {
                return '清空缓存成功';
            } else {
                return '清空失败';
            }
        }
    }

    /**
     * 清空前台生成的资源文件
     */
    public function actionClearAssets()
    {
        if (Yii::$app->request->isPost) {
            if (XFile::delFrontendAssets()) {
                return '清空成功，前台多刷新几次才会生效';
            } else {
                return '清空失败';
            }
        }
    }
}
